package edu.sjsu.itack.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.sjsu.itack.dao.BoardDao;
import edu.sjsu.itack.entity.Board;
import edu.sjsu.itack.entity.User;
import edu.sjsu.itack.util.ITackException;

@WebServlet("/BoardServlet")
public class BoardServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private BoardDao boardDao;

	public BoardServlet() {
		super();
	}

	public void init(){
		this.boardDao = new BoardDao();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String task = request.getParameter("task");
		User user = (User)request.getSession().getAttribute("user");//get user in session
		try {
			switch (task) { //switch based on task type
				case "add": addBoard(request, user);
				break;
				case "update":updateBoard(request, user);
				break;
				case "delete": deleteBoard(request, user);
				break;
			}
		}
		catch (ITackException e){
			response.getWriter().write(e.getMessage());
		}
		
		request.getRequestDispatcher("board.jsp").forward(request, response);//dispatch request to home page if success
	}

	/*
	 * Delete board controller method
	 */
	private void deleteBoard(HttpServletRequest request, User user) throws ITackException {
		int boardId = Integer.parseInt(request.getParameter("boardId"));
		boardDao.deleteBoard(boardId); //call to data access method
	}

	/*
	 * Update board controller method
	 */
	private void updateBoard(HttpServletRequest request, User user) throws ITackException {
		Board board = new Board();
		board.setBoardId(Integer.parseInt(request.getParameter("boardId")));
		board.setName(request.getParameter("ename"));
		board.setDescription(request.getParameter("edescription"));
		board.setType(request.getParameter("etype"));
		board.setUserId(user.getUserId());
		boardDao.updateBoard(board); //call to data access method
	}

	/*
	 * Add board controller board
	 */
	private void addBoard(HttpServletRequest request, User user) throws ITackException {
		Board board = new Board();
		board.setName(request.getParameter("name"));
		board.setDescription(request.getParameter("description"));
		board.setType(request.getParameter("type"));
		board.setUserId(user.getUserId());
		boardDao.createBoard(board); //call to data access method
	}
}
